package com.czy.owner.ui;

import android.content.Intent;
import android.graphics.Bitmap;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.czy.owner.R;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.WebViewRequestParam;
import com.czy.owner.global.Constants;
import com.czy.owner.net.utils.JsonUtil;
import com.czy.owner.rxbus.RxBus;
import com.czy.owner.rxbus.event.CommonEvent;
import com.czy.owner.ui.hotshop.GoodsDetailActivity;
import com.czy.owner.ui.hotshop.GoodsListActivity;
import com.czy.owner.ui.order.OrderActivity;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.SharedPreferencesUtils;
import com.czy.owner.widget.UniversalDialog;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.net.URLDecoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;

/**
 * Created by yang on 2017/12/21.
 */

public class NewWebViewActivity extends BaseActivity {
    @BindView(R.id.webview)
    WebView webview;
    @BindView(R.id.myProgressBar)
    ProgressBar myProgressBar;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    private WebViewRequestParam webViewRequestParam;
    private String title;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_webview;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        myProgressBar.setVisibility(View.GONE);
        if (getIntent().getExtras() == null) {
            PhoneUtils.ShowToastMessage(this, "数据异常");
            finish();
            return;
        }
        webViewRequestParam = (WebViewRequestParam) getIntent().getSerializableExtra(Constants.TRANSMISSION_CONTENT_KEY);
        title = webViewRequestParam.getTitle();
        if (webViewRequestParam != null) {
            toolbarTitle.setText(title);
        }
        webview.setWebViewClient(new NewWebViewActivity.MyWebViewClient());
        WebSettings ws = webview.getSettings();
        ws.setJavaScriptEnabled(true);
        ws.setUseWideViewPort(false);
        ws.setCacheMode(WebSettings.LOAD_NO_CACHE);
        ws.setDomStorageEnabled(true);

        MyLog.e("yang", "Url==" + webViewRequestParam.getUrl());

        if (webViewRequestParam.getRequestMethod() == WebViewRequestParam.REQUEST_POST) {
            webview.postUrl(webViewRequestParam.getUrl(), webViewRequestParam.getParams().getBytes());
        } else {
            webview.loadUrl(webViewRequestParam.getUrl());
        }


        webview.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                // TODO Auto-generated method stub
                super.onProgressChanged(view, newProgress);
                if (newProgress == 100) {
                    if (myProgressBar != null) {
                        myProgressBar.setVisibility(View.GONE);
                    }
                    if (myProgressBar != null) {
                        myProgressBar.setVisibility(View.GONE);
                    }
                } else {
                    myProgressBar.setVisibility(View.VISIBLE);
                    myProgressBar.setProgress(newProgress);

                }
            }

        });


        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (webview.canGoBack()) {  //表示按返回键
                    webview.goBack();   //后退
                    if (toolbarTitle.getText().equals("优卡常见问题解答")) {
                        toolbarTitle.setText("FM908");
                    }
                } else {
                    finish();
                }

            }
        });
    }

    @Override
    protected void updateViews() {

    }


    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, final String url) {
            MyLog.e("yang", "url==" + url);
            if (webViewRequestParam.getRequestMethod() == WebViewRequestParam.REQUEST_POST) {
                view.postUrl(url, webViewRequestParam.getParams().getBytes());
            } else {
                view.loadUrl(url);
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (url.contains("own/receive")) {
                        webview.stopLoading();
                        if (checkLoginState()) {
                            int bindStoreId = (int) SharedPreferencesUtils.getParam(NewWebViewActivity.this, UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_BINDSTOREID, 0);
                            if (bindStoreId != 0) {
                                oneKeyReceive();
                            } else {
                                helpDialog("温馨提示","请先绑定门店才能领取大礼包","确定", "取消");
                            }

                        }
                    } else if (url.contains("own/toComment")) {
                        webview.stopLoading();
                        if (checkLoginState()) {
                            MyLog.e("yang", "登录");
                            getOrders();

                        }

                    } else if (url.contains("pub/goodsView") && url.contains("content")) {
                        MyLog.e("yang", "qqqqqqq");
                        webview.stopLoading();
                        String goodsId = url.substring(url.indexOf("=") + 1, url.indexOf("&"));
                        String content = URLDecoder.decode(url.substring(url.lastIndexOf("=") + 1));
                        Intent intent = new Intent(NewWebViewActivity.this, GoodsListActivity.class);
                        intent.putExtra("goodsType", 0);
                        intent.putExtra("fromType", 1);
                        intent.putExtra("title", content);
                        intent.putExtra("searchStr", content);
                        startActivity(intent);

                    } else if (url.contains("pub/goodsView")) {
                        MyLog.e("yang", "zzzzzzzzzz");
                        Pattern p = Pattern.compile("pub/goodsView\\?goodsId=(\\d*?)$");
                        Matcher m = p.matcher(url);
                        while (m.find()) {
                            final String goodsId = m.group(1);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    webview.stopLoading();
                                    Intent intent = new Intent(NewWebViewActivity.this, GoodsDetailActivity.class);
                                    intent.putExtra("goodsId", Integer.parseInt(goodsId));
                                    startActivity(intent);
                                }
                            });

                        }
                    } else if (url.contains("shop/clubProblem")) {
                        toolbarTitle.setText("优卡常见问题解答");
                    }
                }

            });


            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);

        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);

        }


    }


    //获取订单数量接口
    private void getOrders() {
        mLoadView.ShowLoadView();
        String url = Constants.APP_API_BASE + Constants.OWN_SHOP_GETOWNERORDERS;
        RequestParams params = new RequestParams(url);
        params.addBodyParameter("session", UserHelper.getInstance().getSession(NewWebViewActivity.this));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                MyLog.e("yang", "获取订单数量==" + result);
                int data = JsonUtil.getJsonValuesInt(result, "data");
                MyLog.e("yang", "data==" + data);
                if (data != 0) {
                    Intent intent = new Intent(NewWebViewActivity.this, OrderActivity.class);
                    intent.putExtra("currentId", 4);
                    startActivity(intent);
                } else {
                    handlerDialog("温馨提示", "您还没有购物任何商品,是否返回进行购买商品", "确定", "取消");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                mLoadView.CancleLoadView();
            }
        });
    }


    //领取新人大礼包接口
    private void oneKeyReceive() {
        mLoadView.ShowLoadView();
        String url = Constants.APP_API_BASE + Constants.OWN_SHOP_ONEKEYRECEIVE;
        RequestParams params = new RequestParams(url);
        params.addBodyParameter("session", UserHelper.getInstance().getSession(NewWebViewActivity.this));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                String data = PhoneUtils.checkResponseFlag(NewWebViewActivity.this, result);
                if (data != null) {
                    webview.reload();
                    RxBus.getDefault().post(Constants.REFRESH_SHOPPING_GIFT, new CommonEvent("刷新新人大礼包"));
                    PhoneUtils.ShowToastMessage(NewWebViewActivity.this, "领取成功");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                mLoadView.CancleLoadView();
            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        webview.destroy();
    }

    private void handlerDialog(String title, String msg, String sure, String cancle) {
        new UniversalDialog(NewWebViewActivity.this).builder().setTitle(title)
                .setMsg(msg)
                .setPositiveButton(sure, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                }).setNegativeButton(cancle, new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        }).show();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            if (webview.canGoBack()) {
                webview.goBack();
                if (toolbarTitle.getText().equals("优卡常见问题解答")) {
                    toolbarTitle.setText("FM908");
                }
                return true;
            } else {
                finish();
                return true;
            }

        }
        return false;
    }





    private void helpDialog(String title, String msg, String sure, String cancle) {
        new UniversalDialog(NewWebViewActivity.this).builder()
                .setTitle(title)
                .setMsg(msg)
                .setPositiveButton(sure, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                        RxBus.getDefault().post(Constants.RXBUS_CODE_SWITCH_MAIN_TAB, new CommonEvent("登录未绑定"));
                        MyLog.e("yang", "未绑定");

                    }
                }).setNegativeButton(cancle, new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        }).show();
    }
}
